package com.ruoyi.system.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.ruoyi.system.mapper.RegionMapper;
import com.ruoyi.system.pojo.vo.RegionVO;
import com.ruoyi.system.service.RegionService;
import com.ruoyi.system.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description:
 *
 * @author JourWon
 * @date Created on 2025/5/15
 */
@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RegionMapper regionMapper;

    @DS(value = "slave")
    @Override
    public PageResult<RegionVO> searchRegions(Integer pageIndex, Integer pageSize, String name) {
        // 设置默认值
        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        // 计算总数和总页数
        int totalCount = regionMapper.countRegions(name);
        int totalPage = (int) Math.ceil((double) totalCount / pageSize);

        // 计算偏移量
        int offset = (pageIndex - 1) * pageSize;

        // 查询数据
        List<RegionVO> records = regionMapper.searchRegions(name, offset, pageSize);

        // 构建返回结果
        PageResult<RegionVO> result = new PageResult<>();
        result.setPageIndex(pageIndex);
        result.setPageSize(pageSize);
        result.setTotalPage(totalPage);
        result.setTotalCount(totalCount);
        result.setCurrentPageRecords(records);

        return result;
    }
}
